<?php 

class Db{
	protected static $instance = null;
	
	protected $db = null;
	protected $config = null;
	protected function __construct(){
		$this->config      = new Config();
		$mysqlRead         = $this->config->getKey("database")->getKey("read")->get();
		$readDsn           = "mysql:host={$mysqlRead['DB_HOST']};dbname={$mysqlRead['DB_NAME']}";
		$this->db          = new PDO($readDsn, $mysqlRead['DB_USER'], $mysqlRead['DB_PWD']);
		$this->db->query("set names ".$this->config->getKey("database")->getKey("read")->getKey("CHARSET")->get());
	}
	
	public static function getInstance(){
		if (!self::$instance) {
			self::$instance = new self();
		}
		return self::$instance;
	}
	
	public function query($sql){
		$rs = $this->db->query($sql);
		if($rs)
			$rs->setFetchMode(PDO::FETCH_ASSOC);
		return $rs;
	}
	
	public function __call($name,$arguments){
		if(is_callable(array($this->db,$name))){			
			switch (count($arguments)){
				case 0:
					return $this->db->$name();					
				case 1:
					return $this->db->$name($arguments[0]);
				case 2:
					return $this->db->$name($arguments[0],$arguments[1]);
				case 3:
					return $this->db->$name($arguments[0],$arguments[1],$arguments[2]);
				case 4:
					return $this->db->$name($arguments[0],$arguments[1],$arguments[2],$arguments[3]);
				default:
					return false;
			}
		}
	}
	/**
	 * 获取一个表的所以字段
	 * @param unknown_type $table
	 */
	public function list_fields($table){				
		$rs  = $this->query("DESC ".$table);
		//var_dump($rs);exit;
		$colInfo = $rs->fetchAll();
		$cols    = array();
		if($colInfo){
			foreach($colInfo as $col){
				if(isset($col['Field']))
					$cols[] = $col['Field'];
			}
		}
		return $cols;
	}	
}